package com.bsh.controller.merchant;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.bsh.dto.MerchantEditDto;
import com.bsh.dto.MerchantListQryDto;
import com.bsh.mybatis.model.Merchant;
import com.bsh.mybatis.model.MerchantCategory;
import com.bsh.mybatis.model.Region;
import com.bsh.service.MerchantCategoryService;
import com.bsh.service.MerchantService;
import com.bsh.service.RegionService;
import com.bsh.utils.PageJosnMessage;
import com.bsh.utils.PageTools;
import com.bsh.utils.Pager;
import com.bsh.utils.UploadUtils;
import com.bsh.utils.excel.ColumonCfg;
import com.bsh.utils.excel.ExcelExportor;
import com.mysql.jdbc.StringUtils;

@Controller
public class MerchantController {
	private static Logger log = LoggerFactory.getLogger(MerchantController.class);

	@Autowired
	HttpServletRequest request;
	@Autowired
	HttpServletResponse response;
	@Autowired
	MerchantService merchantServ;
	@Autowired
	RegionService regServ;
	@Autowired
	MerchantCategoryService merchantCateServ;
	
	/**
	 * 商家列表
	 */
	@RequestMapping(value = "/merchant/list")
	public ModelAndView merchantList(@ModelAttribute MerchantListQryDto dto) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/pages/merchant/merchantList");

		String pageStr = request.getParameter("pageIndex");
		Integer pageIndex = Integer.parseInt(StringUtils.isNullOrEmpty(pageStr) ? "1" : pageStr);

		String sizeStr = request.getParameter("pageSize");
		Integer pageSize = Integer.parseInt(StringUtils.isNullOrEmpty(sizeStr) ? "10" : sizeStr);

		Pager pager = new Pager(pageIndex, pageSize);
		List<Map<String, Object>> list = merchantServ.getPage(pager, dto);
		mv.addObject("list", list);
		mv.addObject("pager", pager);
		mv.addObject("qry", dto);
		return mv;
	}
	
	
	/**
	 * 后台管理员充值记录列表--导出
	 * @return 
	 */
	@RequestMapping(value = "/merchant/list/export")
	public ModelAndView merchantListExport(@ModelAttribute MerchantListQryDto dto) {
		ModelAndView mv = new ModelAndView();	
		List<Map<String, Object>> list = merchantServ.getPageExport(dto);
		
		List<ColumonCfg> cfg=new ArrayList<>();
		cfg.add(new ColumonCfg("merchant_name","商户名称",250));
		cfg.add(new ColumonCfg("user_name","用户名",100));
		cfg.add(new ColumonCfg("address","地址",300));
		cfg.add(new ColumonCfg("mobile","电话",100));
		cfg.add(new ColumonCfg("province_name","省份",100));
		cfg.add(new ColumonCfg("city_name","城市",100));
		cfg.add(new ColumonCfg("area_name","地区",100));	
		cfg.add(new ColumonCfg("category_name","经营项目",100));
		cfg.add(new ColumonCfg("status_ch","申请状态",100));
		cfg.add(new ColumonCfg("create_time_ch","申请时间",130));	

		ExcelExportor.exportExcelByCfg("商户列表.xls", cfg, list);
		
		return null;
	}
	

	/**
	 * 添加商家信息--初使化
	 */
	@RequestMapping(value = "/merchant/add")
	public ModelAndView add(@ModelAttribute MerchantEditDto dto) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/pages/merchant/merchantAdd");
		Merchant merchant = new Merchant();
		mv.addObject("merchant", merchant);
		if (merchant != null) {
			List<Region> prov = regServ.getRegionList(1);
			List<Region> city = regServ.getRegionList(null);
			List<Region> area = regServ.getRegionList(null);
			mv.addObject("provList", prov);
			mv.addObject("cityList", city);
			mv.addObject("areaList", area);
		}
		List<MerchantCategory> cateList = merchantCateServ.getCategoryList();
		mv.addObject("cateList", cateList);
		mv.addObject("merchant", dto);
		return mv;
	}

	/**
	 * 添加商家信息--保存
	 */
	@RequestMapping(value = "/merchant/add/save")
	public ModelAndView addSave(@ModelAttribute MerchantEditDto dto) {
		BeanCopier copy = BeanCopier.create(MerchantEditDto.class, Merchant.class, false);
		Merchant merch = new Merchant();
		copy.copy(dto, merch, null);
		merch.setCountry(1);
		Integer res = merchantServ.addMerchant(dto.getUserName(), merch);

		ModelAndView mv = this.add(dto);

		String msg = "";
		if (res == -100)
			msg = PageTools.alert("添加商家信息", "保存失败，用户不存在！", 1000,"saveCallback");
		else if (res == -101)
			msg = PageTools.alert("添加商家信息", "保存失败，商家简称已被使用！", 1000,"saveCallback");
		else if (res == -102)
			msg = PageTools.alert("添加商家信息", "保存失败，商家全称已被使用！", 1000,"saveCallback");			
		else if (res > 0)
			msg = PageTools.alertCloseFraRefresh("添加商家信息", "保存成功！", 1000);
		else
			msg = PageTools.alert("添加商家信息", "保存失败，请稍后重试！", 1000);

		mv.addObject("actionMsg", msg);
		return mv;
	}

	/**
	 * 修改商家信息--初使化
	 */
	@RequestMapping(value = "/merchant/edit/{id}")
	public ModelAndView edit(@PathVariable(value = "id") Integer mid) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("/pages/merchant/merchantEdit");
		Merchant merchant = merchantServ.getMerchant(mid);
		mv.addObject("merchant", merchant);
		if (merchant != null) {
			Integer country = merchant.getCountry();
			List<Region> prov = regServ.getRegionList(country == null ? 1 : country);
			List<Region> city = regServ.getRegionList(merchant.getProvince());
			List<Region> area = regServ.getRegionList(merchant.getCity());
			mv.addObject("provList", prov);
			mv.addObject("cityList", city);
			mv.addObject("areaList", area);
		}
		List<MerchantCategory> cateList = merchantCateServ.getCategoryList();
		mv.addObject("cateList", cateList);
		return mv;
	}

	/**
	 * 修改商家信息--保存
	 */
	@RequestMapping(value = "/merchant/edit/save")
	public ModelAndView editSave(@ModelAttribute MerchantEditDto dto,
			@RequestParam(value = "upimgIdcadA") MultipartFile upimgIdcadA,
			@RequestParam(value = "upimgIdcadB") MultipartFile upimgIdcadB,
			@RequestParam(value = "upimgCert") MultipartFile upimgCert,
			@RequestParam(value = "upimgCover") MultipartFile upimgCover,
			@RequestParam(value = "upimgCoverSmall") MultipartFile upimgCoverSmall) {
		BeanCopier copy = BeanCopier.create(MerchantEditDto.class, Merchant.class, false);
		Merchant merch = new Merchant();
		copy.copy(dto, merch, null);
		merch.setCountry(1);		
		String idcadAUrl= "";
		if (!upimgIdcadA.isEmpty()) {
			idcadAUrl = UploadUtils.save(upimgIdcadA, "/upload/private/merchant");
			merch.setIdcardA(idcadAUrl);
		}		
		String idcadBUrl= "";
		if (!upimgIdcadB.isEmpty()) {
			idcadBUrl = UploadUtils.save(upimgIdcadB, "/upload/private/merchant");
			merch.setIdcardB(idcadBUrl);
		}	
		String imgCertUrl= "";
		if (!upimgCert.isEmpty()) {
			imgCertUrl = UploadUtils.save(upimgCert, "/upload/private/merchant");
			merch.setCertificate(imgCertUrl);
		}	
		String imgCoverUrl= "";
		if (!upimgCover.isEmpty()) {
			imgCoverUrl = UploadUtils.save(upimgCover, "/upload/public/merchant");
			merch.setImgCover(imgCoverUrl);
		}			
		String imgCoverSamllUrl= "";
		if (!upimgCoverSmall.isEmpty()) {
			imgCoverSamllUrl = UploadUtils.save(upimgCoverSmall, "/upload/public/merchant");
			merch.setImgCoverSmall(imgCoverSamllUrl);
		}			
		Integer res = merchantServ.editMerchantExludeImages(merch); 

		ModelAndView mv = edit(dto.getId());
		mv.addObject("merchant", dto);

		String msg = "";
		if (res > 0)
			msg = PageTools.alertCloseFraRefresh("修改商家信息", "保存成功！", 1000);
		else
			msg = PageTools.alert("修改商家信息", "保存失败，请稍后重试！", 1000);

		mv.addObject("actionMsg", msg);
		return mv;
	}	
	
	/**
	 * 设置推荐权重
	 */
	@ResponseBody
	@RequestMapping(value = "/merchant/recomend/sort")
	public PageJosnMessage exists(@RequestParam(value="id") Integer id,@RequestParam(value="sort") Integer sort) {
		Integer res = merchantServ.setRecomendSort(id,sort);
		PageJosnMessage msg = new PageJosnMessage();
		res = (res == null ? 1 : res);
		msg.putData("status", res > 0 ? 1 : 0);
		return msg;
	}	
	
}
